import { BookDocument, Book } from '@app/database/schemas/book.schema';
import { Query, Controller, Get, Param, Patch, Body } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Model } from 'mongoose';

@ApiTags('前台图书模块')
@Controller('books')
export class BooksController {
  constructor(
    @InjectModel('Book') private readonly bookModel: Model<BookDocument>,
  ) {}

  @ApiOperation({ summary: '所有条件图书' })
  @Get()
  async findAll(@Query() query: any) {
    let { like, page, pageSize } = query;
    const where: any = {};
    if (like) {
      where.name = { $regex: like };
    }
    page = parseInt(page);
    pageSize = parseInt(pageSize);
    const items = await this.bookModel
      .find(where)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .sort({ _id: -1 });
    const total = await this.bookModel.countDocuments(where);
    return { items, total };
  }

  @ApiOperation({ summary: '按分类查找图书' })
  @Get('category/:id')
  findByCategory(@Param('id') id: string) {
    return this.bookModel
      .find({ categories: { $all: [id] } })
      .sort({ sales: -1 })
      .limit(4);
  }

  @ApiOperation({ summary: '按ID查找单本图书' })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.bookModel.findOne({ _id: id });
  }

  @ApiOperation({ summary: '更新书籍库存' })
  @Patch(':id')
  async updateOne(@Param('id') id: string, @Body() body: Book) {
    const book = await this.bookModel.findOne({ _id: id });
    book.number -= body.number;
    book.sales += 1;
    book.save();
    return book;
  }
}
